import { defineStore } from 'pinia';
import { getLogList } from '@/api/log';
import { ElMessage } from 'element-plus';

export const useLogStore = defineStore('logStore', {
  state: () => ({
    logs: [],
    total: 0,
    page: 1,
    pageSize: 10,
    loading: false,
    query: {
      startTime: null,
      endTime: null
    }
  }),

  getters: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    hasPrevPage() {
      return this.page > 1;
    },
    hasNextPage() {
      return this.page < this.totalPages;
    },
  },

  actions: {
    // 设置当前页码
    setPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.page = page;
        this.fetchLogs();
      }
    },

    // 设置每页条数
    setPageSize(pageSize) {
      this.pageSize = pageSize;
      this.page = 1;
      this.fetchLogs();
    },

    // 获取日志列表
    async fetchLogs() {
      this.loading = true;
      try {
        const params = {
          pageIndex: this.page,
          pageSize: this.pageSize
        };

        const response = await getLogList(params);

        if (response && response.code === 200 && response.data) {
          this.logs = response.data.items || [];
          this.total = response.data.totalCount || 0;
        } else {
          this.logs = [];
          this.total = 0;
          ElMessage.error('获取日志列表失败: 无效的响应格式');
        }
      } catch (error) {
        const errorMessage = error.message || error.code || '未知错误';
        ElMessage.error('获取日志列表失败: ' + errorMessage);
      } finally {
        this.loading = false;
      }
    },

    // 搜索日志
    async searchLogs(searchParams) {
      this.query = searchParams;
      this.loading = true;
      try {
        const params = {
          ...searchParams,
          pageIndex: this.page,
          pageSize: this.pageSize
        };

        const response = await getLogList(params);

        if (response && response.code === 200 && response.data) {
          this.logs = response.data.items || [];
          this.total = response.data.totalCount || 0;
        } else {
          this.logs = [];
          this.total = 0;
          ElMessage.error('查询日志失败: 无效的响应格式');
        }
      } catch (error) {
        ElMessage.error('查询日志失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },

    // 重置查询条件
    resetQuery() {
      this.query = {
        startTime: null,
        endTime: null
      };
      this.page = 1;
      this.pageSize = 10;
      // 重置后立即获取数据
      this.fetchLogs();
    }
  }
}); 